package net.guerlab.sdk.anubis.accesstoken;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 蜂鸟access_token redis保存实例
 *
 * @author guer
 *
 */
@Component
public class AnubisAccessTokenRedisStorage implements AccessTokenStorage {

    private static final Logger LOGGER = LoggerFactory.getLogger(AnubisAccessTokenRedisStorage.class);

    private static final String KEY = "accesstoken:anubis";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    public AnubisAccessTokenRedisStorage() {
        AccessTokenManager.instance().setStorage(this);
    }

    @Override
    public void put(
            AccessTokenDTO accessTokenDTO) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(KEY, objectMapper.writeValueAsString(accessTokenDTO));
            redisTemplate.expire(KEY, accessTokenDTO.getExpireTime() - System.currentTimeMillis(),
                    TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }

    @Override
    public AccessTokenDTO get() {
        try {
            String data = redisTemplate.opsForValue().get(KEY);

            return objectMapper.readValue(data, AccessTokenDTO.class);
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            return null;
        }
    }

}